package xyz.xiezc.xhttp.common;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.ioc.common.AnnotationHandler;
import xyz.xiezc.ioc.common.BeanDefine;
import xyz.xiezc.xhttp.HttpServer;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wb-xzc291800
 * @date 2019/04/04 16:17
 */
@Slf4j
@Component
public class PathMappingHandler implements AnnotationHandler<PathMapping> {

    @Override
    public Class<PathMapping> getHandlerAnnotation() {
        return PathMapping.class;
    }


    @Override
    public void process(Class<?> aClass, PathMapping annotations, List<BeanDefine> beanDefines) {
        try {
            String prefix = annotations.value();
            //获得这个注解的对象
            List<Object> list;
            if (!beanDefines.isEmpty()) {
                list = beanDefines.stream().map(BeanDefine::getBean).collect(Collectors.toList());
            } else {
                list = CollUtil.newArrayList(aClass.newInstance());
            }
            //获得这个注解中的路径出来方法
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method method : declaredMethods) {
                PathMapping annotation = method.getAnnotation(PathMapping.class);
                if (annotation == null) {
                    continue;
                } else {
                    String suffix = annotation.value();
                    String path = "/" + prefix + "/" + suffix;
                    PathDealPO pathDealPO = new PathDealPO();
                    pathDealPO.setHandler(method);
                    pathDealPO.setHandlObj(list);
                    pathDealPO.setMethod(annotation.method());
                    while (path.contains("//")) {
                        path = path.replaceAll("//", "/");
                    }
                    pathDealPO.setPath(path);
                    HttpServer.pathDealPOMap.put(pathDealPO.getPath(), pathDealPO);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
